import "../static/card_css.css";
import {useEffect, useState} from "react";
import axios from "axios";
import {Layout} from "antd";
import CardList from "../cardList/CardList";
import Comments from "../comments/Commetns";
import {useParams} from "react-router-dom";

let top_user = JSON.parse(localStorage.getItem('userData'))['user'];

// 卡片详情页的数据
export default function CardDetails(){

    const [cards, setCards] = useState([]);
    const [userLikes, setUserLikes] = useState({});  // 当前用户的点赞列表
    const [likesFlag, setLikeFlag] = useState(null);  // 用户判断是否更新了点赞状态的标记
    const [userCollections, setUserCollections] = useState({});  // 用户收藏数据
    const [collectionFlag, setCollectionFlag] = useState(1);  // 控制是否更新组件的状态
    const [commentFlag, setCommentFlag] = useState(null);
    let params = useParams();
    console.log("CardDetails_Props:", params.card_id);
    // 设置卡片的更新界面，依据是是否更新了点赞
    useEffect(() => {
        axios.get('/api/find', {params:{card_id:params.card_id}})
            .then(res => {
                let all_data = res['data'];
                all_data[0]['fields']['card_id'] = params.card_id;  // 卡片细节只有一张卡片
                // all_data.map((item) => {
                //     let k = item['fields'];
                //     k['card_id'] = item['pk'];
                // });
                setCards(all_data);
                // console.log("all_data:", all_data);
            })
    }, [likesFlag, collectionFlag, commentFlag]);   // 如果likesFlag, collectionFlag更改了，那么就重新更新界面

    // 获取当前用户的点赞数据，根据likeFlag来判断是否要重新更新组件
    useEffect(() => {
        let data = localStorage.getItem("userData");
        let user = JSON.parse(data)['user'];
        axios.post('/api/user-likes', {user: user})
            .then((res) => {
                let now = res['data'];
                console.log("now", now);
                setUserLikes(now);
            });
    }, [likesFlag]);

    // 获取用户收藏数据
    useEffect(() => {
        let data = localStorage.getItem("userData");
        let user = JSON.parse(data)['user'];
        console.log(user);
        axios.get("/api/get-user-collections", {
            params:{
                user: user
            }}).then(res => {
            console.log("收藏数据:", res['data']);
            setUserCollections(res['data']);
        })
    }, [collectionFlag]);



    // 处理点赞的函数
    function handleLikes(card_id) {
        let data = localStorage.getItem("userData");  // 获取当前用户的值
        let user = JSON.parse(data)['user'];
        if (userLikes.length > 0) {
            let flag = true;   // 用来控制当前card-id是否是处理到的
            for (let index in userLikes) {
                let right = userLikes[index]['fields'];
                if (right.card_id === card_id) {  // 如果找到了当前点赞的id
                    flag = false;
                    if (right.state === true) {   // 如果是已点赞的状态
                        axios.post('/api/update-likes', {user: user, card_id: card_id, state: true})
                            .then(res => {
                                setLikeFlag(1);
                                console.log(res);
                            })
                    } else {
                        axios.post('/api/update-likes', {user: user, card_id: card_id, state: false})
                            .then(res => {
                                setLikeFlag(2);
                                console.log(res);
                            })
                    }
                }
            }
            if(flag === true) {  // 如果是没有处理到的，则另外进行处理，且state设为true，一个新的变量
                axios.post('/api/update-likes', {user: user, card_id: card_id, state: true})  // 为点赞的，设置为True状态
                    .then(res => {
                        setLikeFlag(3);
                        console.log(res);
                    })
            }
        } else {
            axios.post('/api/update-likes', {user: user, card_id: card_id, state: true})  // 为点赞的，设置为True状态
                .then(res => {
                    setLikeFlag(4);
                    console.log(res);
                })
        }
    }

    // 处理用户收藏的函数
    function handleCollections(card_id) {
        axios.post('/api/update-collections', {user: top_user, card_id: card_id})
            .then(res => {
                console.log(res);
                setCollectionFlag((collectionFlag) => collectionFlag === 1 ? 0 : 1);  // 设置反复横跳的0,1，用来更新界面
            })
    }

    function handleAddComments(card_id) {
        let card_comment = document.getElementById(`card-comment-${card_id}`);
        let display_state = card_comment.style.display;
        if(display_state === "none"){
            card_comment.style.display = "";
        } else {
            card_comment.style.display = "none";
        }
    }

    // 提交评论的数据
    function onPublishComment(card_id){
        let temp_comment = document.getElementById(`input-comment-${card_id}`);
        console.log("运行到obPublishComment了", temp_comment);
        let comment = "";
        if(temp_comment != null ){
            comment = temp_comment.textContent;
        }

        // 发布了之后，就隐藏
        document.getElementById(`card-comment-${card_id}`).style.display = "none";
        axios.post("/api/add-comments", {
            card_id: card_id,
            user: top_user,
            comment: comment
        }).then(res => {
            // console.log(res)
            setCommentFlag((commentFlag) => commentFlag === 1 ? 0 : 1);
        })
    }


    return (
        <Layout>
            <CardList
                cards={cards} handleLikes={handleLikes} userLikes={userLikes} handleCollections={handleCollections}
                userCollections={userCollections} localUser={top_user} handleAddComments={handleAddComments}
                onPublishComment={onPublishComment}
            />
            <Comments />
        </Layout>

    )
}